#include "Mesh.h"

CMesh::CMesh( mString a_sFileName )
{
    m_pObjLoader = new CObjLoader;
    m_pObjLoader->Create(a_sFileName);
    m_uVertexCount = m_pObjLoader->VertexSize();
    m_uIndexCount  = m_pObjLoader->IndexSize();
    m_pTexture     = NULL;
}

mUInt CMesh::NumPolygons( )
{
    return m_uIndexCount;
}

mVoid CMesh::InitMesh( CVShader *a_pVShader )
{
    m_pIAI->CreateVertexBuffer(m_pObjLoader->VertexPtr(), m_uVertexCount * sizeof(TObj_Vertex), sizeof(TObj_Vertex));
    m_pIAI->CreateIndexBuffer(m_pObjLoader->IndexPtr(), m_uIndexCount * sizeof(UINT32), TUINT32);
    m_pVertexDeclaration->AddElement("POSITION", 0, TFLOAT3, 0);
    m_pVertexDeclaration->AddElement("NORMAL"  , 0, TFLOAT3, 0);
    m_pVertexDeclaration->AddElement("TEXCOORD", 0, TFLOAT2, 0);
    m_pVertexDeclaration->Create(a_pVShader->ShaderCode(), a_pVShader->ShaderCodeSize());
}

mVoid CMesh::SendMaterial( CIShader *a_pIShader )
{
    a_pIShader->SendConstantValue("g_vAmbient"  , m_pObjLoader->GetMaterial()->vAmbient   , 3 * sizeof(float), EveryFrame);
    a_pIShader->SendConstantValue("g_vDiffuse"  , m_pObjLoader->GetMaterial()->vDiffuse   , 3 * sizeof(float), EveryFrame);
    a_pIShader->SendConstantValue("g_vSpecular" , m_pObjLoader->GetMaterial()->vSpecular  , 3 * sizeof(float), EveryFrame);
    a_pIShader->SendConstantValue("g_fShininess", &m_pObjLoader->GetMaterial()->fShininess,     sizeof(float), EveryFrame);
    a_pIShader->SendTexture("g_txDiffuse", m_pTexture);
}

mString &CMesh::TexturePath( )
{
    return m_pObjLoader->GetMaterial()->strTexture;
}

mVoid CMesh::SetTexture( CTexture2D *a_pTexture )
{
    m_pTexture = a_pTexture;
}

mVoid CMesh::Render( )
{
    m_pVertexDeclaration->Setup();
    m_pIAI->IASetupBuffers();
    m_pDrawInterface->SetPrimitiveType(TTRIANGLELIST);
    m_pDrawInterface->DrawIndexed(m_uIndexCount, 0, m_uVertexCount, 0);
}

CMesh::~CMesh( )
{
    delete m_pObjLoader;
}